# -*- coding: utf-8 -*-
import cgi
import datetime
import wsgiref.handlers

from google.appengine.ext import db
from google.appengine.api import users
from google.appengine.ext import webapp
from models.enhancedModel import EnhancedModel
from models.shippingOrder import SOModel

import views.Manifest as manifview
import models.manifest as manifmodel
import models.user as um
import decorator as dc

class ManifestContr( webapp.RequestHandler ): # debug
    def debug_self(self, what, action, params, kwds):
        self.response.out.write("(%s)" % what)
        self.response.out.write("\n<br>" + action )
        for (i,p) in enumerate(params):
            self.response.out.write("\n<br>param %d = %s" % (i,p) )
        self.response.out.write("\n<br>kwds=%s" % str(kwds) )
        self.response.out.write("\n<br>url=%s" % ( self.request.url ) )
        self.response.out.write("\n<br>args=%s" % ( self.request.arguments() ) )
        for name in self.request.arguments():
            self.response.out.write("\n<br>arg: <b>%s</b>=%s" % ( name, self.request.get(name) ) )

        self.response.out.write( repr(type(manifview)) )   ; self.response.out.write("\n<br>")
        self.response.out.write( repr(manifview.__name__) ); self.response.out.write("\n<br>")
        self.response.out.write( repr(manifview.__path__) ); self.response.out.write("\n<br>")
        self.response.out.write( repr(manifview.__doc__) ) ; self.response.out.write("\n<br>")
        self.response.out.write( repr(manifview.__file__) ); self.response.out.write("\n<br>")
        self.response.out.write( str((type(manifview),dir(manifview)))) ; self.response.out.write("\n<br>")

    @dc.decorate
    def get(self, action, *params, **kwds):

        #self.debug_self('get', action, params, kwds)

        showArchival = self.request.get( 'archival' ) == 'True'

        permissionName = {"show1" : "mfShow",
                       "showAll" : "mfShow",
                       "edit" : "mfEdit",
                       "delete" : "mfDelete",
                       "new": "mfNew"
                       }
        
        if not um.UserModel.currentHasPermission(permissionName[action]):
          self.response.out.write("<font color=\"red\"><b>You have no rights to do this action.</b></font>")
          return

        if action == 'show1': # show1/id/number # DONE
            query = manifmodel.ManifestModel.all()
            query.filter( 'ident =', int( params[0] ) )

            if not showArchival:
                query.filter( 'archival =', False )

            for (i, manif) in enumerate( query ):
                self.response.out.write( manifview.show1(um.UserModel.userRole(), manif ) )

        elif action == 'showAll': #showAll # DONE
            query = manifmodel.ManifestModel.all()

            if not showArchival:
                query.filter( 'archival =', False )
            ident = self.request.get('ident')
            if ident:
              query.filter( 'ident =', int(ident) )
            origin = self.request.get('origin')
            if origin:
              query.filter( 'startAddress =', origin )
            destination = self.request.get('destination')
            if destination:
              query.filter( 'destAddress =', destination )

            self.response.out.write( manifview.showAll(um.UserModel.userRole(), list(query) ) )

        elif action == 'edit':#edit/id/number # DONE
            ident = int( params[0] )
            showError = self.request.get( 'error' ) == 'True'
            wrong = self.request.get('wrong')
            orders = cgi.escape(self.request.get( 'orders' ))
            if showError:
               if not wrong:
                 self.response.out.write("<font color=\"red\"><b>No shipping orders were send.</b></font>")
               else:
                 self.response.out.write("<font color=\"red\"><b>Following shipping orders numbers are inwalid:<br>%s</b></font>" % wrong)
            if not orders:
               orders = ''
            record = EnhancedModel.queryLatest( manifmodel.ManifestModel, ident).get()
            self.response.out.write( manifview.edit(record, self.startAddressSelect( record.startAddress ), self.destAddressSelect( record.destAddress )))

        elif action == 'delete': # delete/id/number # DONE
            manif = EnhancedModel.queryLatest( manifmodel.ManifestModel, ident=int(params[0])).get()
            if manif != None:
               self.response.out.write( manifview.delete( manif ))
            else:
               self.response.out.write("<font color=\"red\"><b>This manifest has been deleted before!</b></font>")
            

        elif action == 'new': # new/ # DONE
            showError = self.request.get( 'error' ) == 'True'
            wrong = self.request.get('wrong')
            orders = cgi.escape(self.request.get( 'orders' ))
            if showError:
               if not wrong:
                 self.response.out.write("<font color=\"red\"><b>No shipping orders were send.</b></font>")
               else:
                 self.response.out.write("<font color=\"red\"><b>Following shipping orders numbers are invalid:<br>%s</b></font>" % wrong)
            if not orders:
               orders = ''
            self.response.out.write( manifview.new( self.startAddressSelect(), self.destAddressSelect(), orders ) )

    def post(self, action, *params, **kwds):
        permissionName = {"show1" : "mfShow",
                       "showAll" : "mfShow",
                       "edit" : "mfEdit",
                       "delete" : "mfDelete",
                       "new": "mfNew"
                       }
        
        if not um.UserModel.currentHasPermission(permissionName[action]):
          self.response.out.write("<font color=\"red\"><b>You have no rights to do this action.</b></font>")
          return

        self.debug_self('post', action, params, kwds)

        if action == 'new': # new/ # sprawdzanie czy wprowadzone numery SO są poprawne # DONE
            orders = cgi.escape(self.request.get( 'orders' ))
            startAddr = cgi.escape(self.request.get( 'startAddr' ))
            if startAddr == 'other':
                startAddr = cgi.escape(self.request.get( 'startAddrOther' ))
            destAddr = cgi.escape(self.request.get( 'destAddr' ))
            if destAddr == 'other':
                destAddr = cgi.escape(self.request.get( 'destAddrOther' ))
            ords = map( int, filter(None, [(x.strip()) for x in orders.split(",")] ))
            err = False
            wrong = ""
            for order in ords:
               so = SOModel.queryLatest(SOModel, ident=order).get()
               if not so:
                  err = True
                  wrong += (str(order) + ",")
            if not err:
               if len(ords)==0:
                  self.redirect('/manifest/new?error=True')
               else:
                 manif = manifmodel.ManifestModel( orders = ords, startAddress = startAddr, destAddress = destAddr)
                 manif.put()
                 ident = manif.ident
                 self.redirect('/manifest/show1/id/%d?done=True' % ident) 
            else:
               self.redirect('/manifest/new?error=True&wrong=%s&orders=%s' % (wrong[:-1], orders))

        elif action == 'edit': # edit/id/number # DONE
            old = EnhancedModel.queryLatest( manifmodel.ManifestModel, ident = int( params[0] ) ).get() 
            orders = cgi.escape(self.request.get( 'orders' ))
            startAddr = cgi.escape(self.request.get( 'startAddr' ))
            if startAddr == 'other':
                startAddr = cgi.escape(self.request.get( 'startAddrOther' ))
            destAddr = cgi.escape(self.request.get( 'destAddr' ))
            if destAddr == 'other':
                destAddr = cgi.escape(self.request.get( 'destAddrOther' ))
            ords = map( int, filter(None, [(x.strip()) for x in orders.split(",")] ))
            err = False
            wrong = ""
            for (i,order) in enumerate( ords ):
               so = SOModel.queryLatest(SOModel, ident=order).get()
               if not so:
                  err = True
                  wrong += (str(order) + ",")
            if not err:
               if len(ords)==0:
                  self.redirect('/manifest/new?error=True')
               else:
                new = manifmodel.ManifestModel( orders = ords, startAddress = startAddr, destAddress = destAddr)
                new.ident = old.ident
                EnhancedModel.deprecateOldVersion( new, old )
                self.redirect('/manifest/show1/id/%d?done=True' % ident) 
            else:
                self.redirect('/manifest/new?error=True&wrong=%s&orders=%s' % (wrong[:-1], orders))

        elif action == 'delete': # delete/id/number # DONE
            old = EnhancedModel.queryLatest( manifmodel.ManifestModel, ident=int(params[0])).get()
            ident = old.ident
            if self.request.get('delete') == "NO":
              self.redirect('/manifest/show1/id/%d' % ident)
            else:
              old.deleteInstance()
              self.redirect('/manifest/show1/id/%d?archival=True&done=True' % ident)

        elif action == 'showAll':  # DONE
           arch = cgi.escape(self.request.get('archival'))
           if not arch:
              arch = 'False'		   
           opt = '?archival='+arch
           ident = self.request.get('ident')
           if ident:
              opt += '&ident='+ cgi.escape(ident)
           origin = self.request.get('origin')
           if origin:
              opt += '&origin='+ cgi.escape(origin)
           destination = self.request.get('destination')
           if destination:
              opt += '&destination='+ cgi.escape(destination)
			  
           self.redirect('/manifest/showAll'+opt)

    def placesList(self):
       query = manifmodel.ManifestModel.all()

       q = []
       for result in query:
          try:
             i = q.index(result.startAddress)
          except ValueError:
             q.append(result.startAddress)
          try:
             i = q.index(result.destAddress)
          except ValueError:
             q.append(result.destAddress)

       return q

    def startAddressSelect ( self, selected = -1 ):
        select = '''
            <script>
                function toggleOtherStartAddr(sel)
                {
                    var div = document.getElementById('otherStartAddr')
                    if ( sel.options[sel.selectedIndex].value == "other" )
                    {
                        div.style.display = "block"
                    }
                    else
                    {
                        div.style.display = "none"
                    }
                }
            </script>
        ''' 
        select += '<select name="startAddr" onchange="toggleOtherStartAddr(this);" id="startAddrselect">'
        query = self.placesList()
        for result in query:
            if result == selected:
                curSelected = 'selected' 
            else:
                curSelected = ''
            select += '<option value="%s" %s>%s</option>' % (result, curSelected, result)
        select += '<option value="other">Other...</option>'
        select += '</select>'
        select += '''
            <div id="otherStartAddr" style='margin: 5px; padding: 5px; border: 1px solid #cccccc; display: none'>
                <input type='text' name='startAddrOther' value=''>
            </div>
            <script>
                 toggleOtherStartAddr(document.getElementById('theselect'))
            </script>
        '''
        return select
        
    def destAddressSelect ( self, selected = -1 ):
        select = '''
            <script>
                function toggleOtherDestAddr(sel)
                {
                    var div = document.getElementById('otherDestAddr')
                    if ( sel.options[sel.selectedIndex].value == "other" )
                    {
                        div.style.display = "block"
                    }
                    else
                    {
                        div.style.display = "none"
                    }
                }
            </script>
        ''' 
        select += '<select name="destAddr" onchange="toggleOtherDestAddr(this);" id="destAddrselect">'
        query =  self.placesList()
        for result in query:
            if result == selected:
                curSelected = 'selected' 
            else:
                curSelected = ''
            select += '<option value="%s" %s>%s</option>' % (result, curSelected, result)
        select += '<option value="other">Other...</option>'
        select += '</select>'
        select += '''
            <div id="otherDestAddr" style='margin: 5px; padding: 5px; border: 1px solid #cccccc; display: none'>
                <input type='text' name='destAddrOther' value=''>
            </div>
            <script>
                 toggleOtherStartAddr(document.getElementById('theselect'))
            </script>
        '''
        return select
